#include "JobManager.h"

Job::Job() {
	id = -1;
}
Job::Job(int _id ) {
	id = _id;
}
void Job::operator()(void) {
	std::cout << this;
}
	


std::ostream & operator <<(std::ostream &os, const Job & j) {
	return os << "Job - " << j.id;
}



JobManager::JobManager() {
	max_queue_size = 5;
	done = false;
}

JobManager::JobManager(int size){
	JobManager();
	this->max_queue_size = size;	
}

//JobManager::JobManager(const JobManager &other) {
//	done = other.done;
//	max_queue_size = other.max_queue_size;	
//}

void JobManager::addJob(Job* job) {
	Lock lock(monitor);
	while (job_queue.size() >= max_queue_size) {
		buffer_full.wait(lock);
	}
	job_queue.push(*job);
	printf("added job - %d\n", job->id);
	buffer_empty.notify_one();
}

Job JobManager::getJob() {
	Lock lock(monitor);
	while (job_queue.size() <= 0) {
		buffer_empty.wait(lock);
		if (done)
			return NULL;
	}
	Job j;
	j = job_queue.front();
	job_queue.pop();
	std::cout << j;
	j.print();
	buffer_full.notify_one();
	return j;
}

void JobManager::run() {
	while (!done) {
		Job j = getJob();
		std::cout << j << "\n";
	}
}

void JobManager::operator ()() {
	this->run();
}


void JobManager::finish() {
	printf("finishing...\n");
	done = true;
	buffer_empty.notify_one();
	printf("done\n");
}
